package org.fastsyncer.rest.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.entity.RestResult;
import org.fastsyncer.common.util.JsonUtil;
import org.fastsyncer.core.service.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/system")
public class SystemController {

	private static final Logger logger = LoggerFactory.getLogger(SystemController.class);

    @Autowired
    private ConfigService config;
    
	@RequestMapping("")
	public String index(ModelMap model) {
		try {
			model.addAttribute("params", JsonUtil.objToJson(config.getSystemParams()));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
		}
		return "system/index";
	}

	/**
	 * 获取系统参数
	 * @Title: update 
	 * @Description: 获取系统参数
	 * @param request
	 * @return: RestResult
	 */
	@RequestMapping(value = "/get", method = { RequestMethod.POST })
	@ResponseBody
	public RestResult get(HttpServletRequest request) {
		try {
			return RestResult.restSuccess(config.getSystemParams());
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getMessage());
		}
	}
	
	/**
	 * 系统参数
	 * @Title: update 
	 * @Description: 修改系统参数
	 * @param request
	 * @param params JSON格式的系统参数，例如：{"limit":100,"session_time":30,...}
	 * @return: RestResult
	 */
	@RequestMapping(value = "/update", method = { RequestMethod.POST })
	@ResponseBody
	public RestResult update(HttpServletRequest request, @RequestParam(value = "params") String params) {
		try {
			if (StringUtils.isBlank(params)) {
				throw new NullPointerException("系统参数错误.");
			}
			return RestResult.restSuccess(config.updateSystemParams(params));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getMessage());
		}
	}
	
}
